<?php
# 2008.0104.0104

# This is an example of the cron job you need to add. The path to PHP may be different.
# The path to the script itself will be different.
# * * * * * /usr/local/php5/bin/php /home/dogstardata/dogstardata.org/trackerfetch.php

# This directory must have permissions that allow the script to write 
# to it when run as a cron job. chmod 777 will do.
$base_dir = "/var/www/html/tracker";

# If your PHP does not allow file_get_contents from a remote server
# set this to 1, otherwise set it to 0.
$use_curl = 0;

# This is how many times the script should loop before exiting.
$iterations = 7;

# And this is how long it should sleep between fetching the file.
# Set iterations to 7 and interval to 9 for a cron job that runs
# every minute.
$interval = 9;

# Each project that uses this data is given a different filename to
# use which is symbolically linked to trcker.txt. This makes it easy
# to see how much traffic a project is generating and to narrow down
# problems with particular projects. Every server in the round robin
# for dogstardata.org should set this to 1.
$create_symbolic_links = 1;

# The DogstarRadio tracker uses unix line breaks, the stream_ON tracker
# uses PC line breaks. You can set the line breaks for your feed or
# leave them as they are from whichever source you are using. To set the
# line breaks change $set_line_breaks to 1. TO leave line breaks as they
# are change $set_line_breaks to 0. To control which line breaks your feed
# will have set $line_breaks to 'lf' for Unix or 'crlf' for PC. Unix line
# breaks will result in a file size that is 1 kB less which can be
# significant for a file served millions of times.
$set_line_breaks = 1;
$line_breaks = 'lf';


# End of configuration
######################

# Check for the existence and permissions of the $base_dir
if(! is_writable($base_dir)) {
   print 'Error: The $base_dir directory, ' . $base_dir . ' is not writable by this script.<p>';
   if(!file_exists($base_dir)) {
      print 'Error: The $base_dir directory, ' . $base_dir . ' does not exist on this server.<p>';
   }
   else {
      $dirstat = stat($base_dir);
      $dirowner = posix_getpwuid($dirstat['uid']);
      $processUser = posix_getpwuid(posix_geteuid());
      print "This script is being run as " . $processUser['name'] . ".<p>";
      print "The directory $base_dir is owned by" . $dirowner['name'] . ".<p>";
      if($dirowner !=  $processUser['name']) {
         print 'You should either change the owner of the directory to '. $processUser['name'];
         print ' and chmod the directory to 755 or simply chmod the directory to 777<p>';
      }
      else {
         print 'You should chmod the directory to 755 or 777.<p>';
      }
   }
   exit;
}
         
   
# Fetch updated sources and symbolic link data every hour
if(time() - 3600 > filemtime($base_dir . "/tracker_sources.txt")) {
   $sourl = "http://server.dogstardata.org/tracker_sources.txt";
   $slurl = "http://server.dogstardata.org/symbolic_links.txt";
   if($use_curl) {
      if($create_symbolic_links) {
         $ch = curl_init($slurl);
         $fp = fopen($base_dir . "/symbolic_links.txt", "w");

         curl_setopt($ch, CURLOPT_FILE, $fp);
         curl_setopt($ch, CURLOPT_HEADER, 0);
 
         curl_exec($ch);
         fclose($fp);
         curl_close($ch);
      }
      
      $ch = curl_init($sourl);
      $fp = fopen($base_dir . "/tracker_sources.txt", "w");

      curl_setopt($ch, CURLOPT_FILE, $fp);
      curl_setopt($ch, CURLOPT_HEADER, 0);

      curl_exec($ch);
      fclose($fp);
      curl_close($ch);
   }
   else {
      if($create_symbolic_links) {
         print 'Fetch Symbolic_Links.<p>';
         $sl = file_get_contents($slurl);
         print 'Fetch Symbolic_Links complete.<p>';
         file_put_contents_ex($base_dir . "/symbolic_links.txt", $sl);
         print 'Symbolic_Links written.<p>';
      }
      
      $so = file_get_contents($sourl);
      file_put_contents_ex($base_dir . "/tracker_sources.txt", $so);
   }
   
   if($create_symbolic_links) {
      if(! file_exists($base_dir . "/tracker.txt")) {
         touch($base_dir . "/tracker.txt");
      }
      $symbolic_links = file($base_dir . "/symbolic_links.txt");
      foreach($symbolic_links as $symbolic_link) {
         if(! file_exists($base_dir . "/" . rtrim($symbolic_link))) {
            symlink($base_dir . "/tracker.txt", $base_dir . "/" . rtrim($symbolic_link));
         }
      }
   }
}

# Get the current tracker source
$url = file_get_contents($base_dir . "/tracker_source.txt");
if(strlen($url) < 5) {
  $tracker_sources = file($base_dir . "/tracker_sources.txt");
  $url = $tracker_sources[0];
  file_put_contents_ex($base_dir . "/tracker_source.txt", $url);
}

# Loop through fetching tracker data
$count = 0;
if($use_curl) {
   $ch = curl_init($url);
   while($count < $iterations) {
      
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HEADER, 0);
   
      $tracker = curl_exec($ch);
     
      if($set_line_breaks) {
         $tracker = set_line_breaks($tracker,$line_breaks);
      }

      $samesize = write_file($base_dir, $samesize, $tracker);
      sleep($interval);
      $count++;
      if($count % 10 == 0) {
         $url = check_source($url,10,$samesize);
         $samesize = 0;
      }
   }
   curl_close($ch);
}
else {
   while($count < $iterations) {
      print 'Getting PDT Data<p>';
      $tracker = file_get_contents($url);
      if($set_line_breaks) {
         $tracker = set_line_breaks($tracker, $line_breaks);
      }
      $samesize = write_file($base_dir, $samesize, $tracker);
      sleep($interval);
      $count++;
      if($count % 10 == 0) {
         $url = check_source($url,10,$samesize);
         $samesize = 0;
      }
   }
}
$url = check_source($url,$iterations,$samesize);

# Check to make sure source is functional
function check_source($url, $iterations, $samesize) {
   if($samesize == $iterations) {
      $tracker_sources = file($base_dir . "/tracker_sources.txt");
      foreach($tracker_sources as $source) {
         if($url != $source) {
            $url = $source;
            break;
         }
      }
      file_put_contents_ex($base_dir . "/tracker_source.txt", $url);
   }
   return($url);
}

# Write to trackertmp.txt then rename it to tracker.txt
function write_file($base_dir, $samesize, $tracker) {
  file_put_contents_ex($base_dir . "/trackertmp.txt", $tracker);
  if(filesize($base_dir . "/trackertmp.txt") == filesize($base_dir . "/tracker.txt")) {
    $samesize++;
  }
  rename($base_dir . "/trackertmp.txt", $base_dir . "/tracker.txt");
  return($samesize);
}

# Change line breaks if needed
function set_line_breaks($tracker, $line_breaks) {
   if($line_breaks == 'crlf') {
      $tracker = preg_replace('/\r?\n/',"\r\n",$tracker);   
   }
   else {
      $tracker = preg_replace('/\r\n?/',"\n",$tracker);
   }
   return($tracker);
}

# PHP4 compatible version of file_put_contents
function file_put_contents_ex($n, $d) {
    $f = @fopen($n, 'w');
    if ($f === false) {
        print 'Could not create file!<p>';
        return 0;
    } else {
        if (is_array($d)) $d = implode($d);
        $bytes_written = fwrite($f, $d);
        fclose($f);
        return $bytes_written;
    }
}

?>
